// 此代码由ai生成，源码是nim写的
#include <iostream>
#include <fstream>
#include <string>
#include <codecvt>
#include <locale>

// Function to convert a string from one encoding to another
std::string convertEncoding(const std::string& input, const std::string& fromEncoding, const std::string& toEncoding) {
    if (fromEncoding == "GBK" && toEncoding == "UTF-8") {
        std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter;
        std::wstring wide = converter.from_bytes(input);
        return converter.to_bytes(wide);
    } else if (fromEncoding == "shift-jis" && toEncoding == "UTF-8") {
        std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter;
        std::wstring wide = converter.from_bytes(input);
        return converter.to_bytes(wide);
    }
    // Add more encoding conversions as needed
    return input;
}

void create_txtx(const std::string& filename, const std::string& data, const std::string& encoding) {
    char head[100] = {0};
    // Assuming encoding is a string representation of the encoding name
    for (size_t i = 0; i < encoding.size(); ++i) {
        head[i] = encoding[i];
    }

    std::string encodeStr = convertEncoding(data, encoding, "UTF-8");

    std::ofstream file(filename, std::ios::binary);
    if (!file) {
        std::cerr << "Error opening file for writing: " << filename << std::endl;
        return;
    }

    file.write(head, sizeof(head));
    file.write(encodeStr.c_str(), encodeStr.size());
    file.close();
}

std::string get_encode(const std::string& filename) {
    char head[100] = {0};

    std::ifstream file(filename, std::ios::binary);
    if (!file) {
        std::cerr << "Error opening file for reading: " << filename << std::endl;
        return "";
    }

    file.read(head, sizeof(head));
    file.close();

    std::string encode(head, sizeof(head));
    return encode;
}

void test() {
    create_txtx("chinese.txtx", "中文测试", "GBK");
    create_txtx("japanese.txtx", "ああああ", "shift-jis");
    std::cout << get_encode("test/chinese.txtx") << std::endl;
    std::cout << get_encode("test/japanese.txtx") << std::endl;
}

int main() {
    test();
    return 0;
}